package api

import (
	"gitee.com/zhaokangming/tiny-ticktok/model"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/app"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/constants"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/errcode"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/util/auth"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/util/convert"
	"gitee.com/zhaokangming/tiny-ticktok/service"
	"github.com/gin-gonic/gin"
)

type UserListResponse struct {
	model.Response
	UserList []model.User `json:"user_list"`
}

// RelationAction create or delete relation
func RelationAction(c *gin.Context) {
	claims, ok := c.Value("claims").(*auth.Claims)
	if !ok {
		app.WriteResponse(c, errcode.ErrAuthCheckToken, nil)
		return
	}

	// 提取想要关注者的id
	targetID, ok := c.GetQuery("to_user_id")
	if !ok {
		app.WriteResponse(c, errcode.ErrParamTypeError, nil)
		return
	}

	// 判断请求的参数，action为1为关注，0为取消关注
	action, ok := c.GetQuery("action_type")
	if !ok {
		app.WriteResponse(c, errcode.ErrParamTypeError, nil)
		return
	}

	// 自己不能对自己进行关注（自然也到不了取消关注）
	if claims.ID == convert.StrTo(targetID).MustInt64() {
		app.WriteResponse(c, errcode.ErrParamTypeError, nil)
		return
	}

	// 点赞的情况
	if action == constants.Action {
		err := service.Follow(c, claims.ID, convert.StrTo(targetID).MustInt64())
		app.WriteResponse(c, err, nil)
		return
	}

	if action == constants.ActionCancel {
		err := service.CancelFollow(c, claims.ID, convert.StrTo(targetID).MustInt64())
		app.WriteResponse(c, err, nil)
		return
	}

	app.WriteResponse(c, errcode.ErrParamTypeError, nil)
}

// FollowList get follow list of given user id
func FollowList(c *gin.Context) {
	claims, ok := c.Value("claims").(*auth.Claims)
	if !ok {
		app.WriteResponse(c, errcode.ErrAuthCheckToken, nil)
		return
	}

	userID, ok := c.GetQuery("user_id")
	if !ok {
		app.WriteResponse(c, errcode.ErrParamTypeError, nil)
		return
	}

	var targetID int64
	if userID == "0" {
		targetID = claims.ID
	} else {
		targetID = convert.StrTo(userID).MustInt64()
	}

	res, err := service.GetFollowOrFans(c, constants.FollowKey, claims.ID, targetID)
	app.WriteResponse(c, err, res)
}

// FollowerList get fans list of given user id
func FollowerList(c *gin.Context) {
	claims, ok := c.Value("claims").(*auth.Claims)
	if !ok {
		app.WriteResponse(c, errcode.ErrAuthCheckToken, nil)
		return
	}

	userID, ok := c.GetQuery("user_id")
	if !ok {
		app.WriteResponse(c, errcode.ErrParamTypeError, nil)
		return
	}

	var targetID int64
	if userID == "0" {
		targetID = claims.ID
	} else {
		targetID = convert.StrTo(userID).MustInt64()
	}

	res, err := service.GetFollowOrFans(c, constants.FansKey, claims.ID, targetID)
	app.WriteResponse(c, err, res)
}
